package com.ruoyi.mall.app.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Value("${spring.elasticsearch.rest.hostname}")
    private String hostname;

    @Value("${spring.elasticsearch.rest.port}")
    private int port;

    @Value("${spring.elasticsearch.rest.scheme}")
    private String scheme;

    @Value("${spring.elasticsearch.rest.connection-timeout}")
    private String connectionTimeout;

    @Value("${spring.elasticsearch.rest.read-timeout}")
    private String readTimeout;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 解析超时时间（单位：毫秒）
        int connTimeout = Integer.parseInt(connectionTimeout.replace("s", "")) * 1000;
        int readTimeoutMs = Integer.parseInt(readTimeout.replace("s", "")) * 1000;

        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(hostname, port, scheme))
                        .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                                .setConnectTimeout(connTimeout)
                                .setSocketTimeout(readTimeoutMs))
        );
    }
}
